﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;

namespace TCCT_CTC_CSDLDangVienV1.HeThong
{
    public partial class frmDoiMatKhau : frmBase
    {
        public frmDoiMatKhau()
        {
            InitializeComponent();
        }

        private void frmDoiMatKhau_Load(object sender, EventArgs e)
        {
            ApplyUI();
        }

        private void ApplyUI()
        {
            UI.TextBox.ApplyPassword(txtReNewPassword);
            UI.TextBox.ApplyPassword(txtOldPassword);
            UI.TextBox.ApplyPassword(txtNewPassword);
            UI.Button.ApplyAccept(btnChapNhan);
            UI.Button.ApplyCancel(btnBoQua);
        }


        private void btnBoQua_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private bool IsInvalid()
        {
            bool isValid = true;
            ValidationMessage = null;
            AppendValidationMessage("Các dữ liệu không hợp lệ: ");


            if (txtOldPassword.Text != MyCommon.CurrentPassword)
            {
                AppendValidationMessage("Mật khẩu cũ không đúng");
                isValid = false;
            }

            if (txtNewPassword.Text != txtReNewPassword.Text)
            {
                AppendValidationMessage("Nhập lại mật khẩu mới không đúng");
                isValid = false;
            }

            //Hiện thông báo lỗi khi isValid=false
            if (!isValid)
                ShowValidationMessage();

            return isValid;
        }

        private void btnChapNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (!IsInvalid()) return;

                string sql = "Update tblUser Set Password=@Password, UserID=@UserID Where ID=@ID ";

                List<SqlParameter> arrParameters = new List<SqlParameter>();
                arrParameters.Add(SqlHelper.CreateParameterObject("@Password", SqlDbType.NVarChar, ParameterDirection.Input, EncryptSMSB.Encrypt(txtNewPassword.Text)));
                arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.BigInt, ParameterDirection.Input, MyCommon.CurrentUserID));
                arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.BigInt, ParameterDirection.Input, MyCommon.CurrentUserID));

                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);

                MyCommon.CurrentPassword = txtNewPassword.Text;

                ShowInfoMessage("Đổi mật khẩu thành công");
                this.Close();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }

        }

    }
}